package org.budo.poi.pdf;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.ss.usermodel.Sheet;
import org.budo.poi.AbstractWorkbook;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.FontSelector;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * @author lmw
 * @see https://www.cnblogs.com/canmeng-cn/p/9078089.html
 */
public class PdfWorkbook extends AbstractWorkbook {
    @Override
    public Sheet createSheet(String sheetname) {
        PdfSheet sheet = new PdfSheet(sheetname);
        this.getSheets().put(sheetname, sheet);
        return sheet;
    }

    @Override
    public void write(OutputStream outputStream) throws IOException {
        FontSelector fontSelector = new FontSelector();
        for (String font : FontFactory.getRegisteredFonts()) {
            fontSelector.addFont(FontFactory.getFont(font));
        }

        Sheet sheet = this.getSheetAt(0);

        int firstRow = sheet.getFirstRowNum();
        int lastRow = sheet.getLastRowNum();

        short firstCell = sheet.getRow(0).getFirstCellNum();
        short lastCell = sheet.getRow(0).getLastCellNum();

        PdfPTable pdfPTable = new PdfPTable(lastCell+1);
        for (int i = firstRow; i < lastRow; i++) {
            for (int j = firstCell; j <= lastCell; j++) {
                String cellValue = sheet.getRow(i).getCell(j).getStringCellValue();
                if (null == cellValue || cellValue.trim().isEmpty()) {
                    pdfPTable.addCell(cellValue);
                    continue;
                }

                Phrase phrase = fontSelector.process(cellValue);
                pdfPTable.addCell(phrase);
            }
        }

        Document document = new Document();
        this.pdfWriterGetInstance(outputStream, document);
        document.open();
        this.documentAdd(document, pdfPTable);
        document.close();
    }

    private void documentAdd(Document document, PdfPTable pdfPTable) {
        try {
            document.add(pdfPTable);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    private void pdfWriterGetInstance(OutputStream outputStream, Document document) {
        try {
            PdfWriter.getInstance(document, outputStream);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }
}